package xyz.labmem.main.tool;

import cn.hutool.core.io.FileTypeUtil;
import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * ImgUtil类增加一些方法
 * Created by Lty
 * Created in 14:47 2020-3-3
 */
public class ImgUtil extends cn.hutool.core.img.ImgUtil {

    //压缩图片方法
    public static void zip(File img, File newImg, double scale, double outputQuality, String outputFormat) throws IOException {
        Thumbnails.of(img)
                .scale(scale)
                .outputQuality(outputQuality)
                .outputFormat(outputFormat)
                .toFile(newImg);
    }

    public static void zip(File img, File newImg, String outputFormat) throws IOException {
        zip(img, newImg, 1f, 0.45f, outputFormat);
    }

    public static void zip(File img, String outputFormat) throws IOException {
        zip(img, img, 1f, 0.45f, outputFormat);
    }

    public static void zipTojpg(File img, File newImg) throws IOException {
        zip(img, newImg, 1f, 0.45f, "jpg");
    }

    public static void zipTojpg(File img) throws IOException {
        zipTojpg(img, img);
    }
    //压缩图片方法        END

    /**
     * 图片转base64字符串
     *
     * @param imgFile 图片文件
     * @return
     */
    public static String imageToBase64Str(File imgFile) {
        if (imgFile == null)
            return null;
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        var encoder = Base64.getEncoder();
        return "data:image/" + FileTypeUtil.getType(imgFile) + ";base64," + encoder.encodeToString(data);
    }
}
